<template>
  <div :class="hideStyle ? '' : 'box_wrap'">
    <div v-if="!hideTitle" class="box_wrap_title">
      会员信息
    </div>
    <el-form ref="refMemberInfo" :model="vo" :size="formSize" label-width="210px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="所属协会" prop="parentTAProvinceCode" :rules="vo.ctaMemberStatusCode === 'None' || !vo.ctaMemberStatusCode ? [] : formRules.parentTAProvinceCode">
            <el-select v-if="!isCheck" v-model="vo.parentTAProvinceCode" class="gl_mr_15" placeholder="请选择所在省" filterable @change="onChangeProvinces">
              <el-option v-for="item in provinces" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
            <el-select v-if="!isCheck" v-model="vo.parentTACityCode" class="gl_mr_15" placeholder="请选择所在市" filterable @change="onChangeCities">
              <el-option v-for="item in cities" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
            <el-select v-if="!isCheck" v-model="vo.parentTACountyCode" class="gl_mr_15" placeholder="请选择所在县" filterable>
              <el-option v-for="item in counties" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
            <span v-if="isCheck">{{ provincesName }} {{ cityName }} {{ countyName }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="中国跆协个人会员状态">
            <el-select v-if="false" v-model="vo.ctaMemberStatusCode" style="width: 100%" class="gl_mr_15" placeholder="请选择个人会员状态" @change="onChangeStatusCode">
              <el-option v-for="item in dict.registerMemberStatus" :key="item.code" :label="item.value" :value="item.code" />
            </el-select>
            <span v-else>{{ registerMemberStatusName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="中国跆协会员号" prop="ctaMemberId" :rules="vo.ctaMemberStatusCode === 'None' || !vo.ctaMemberStatusCode ? [] : formRules.ctaMemberId">
            <el-input v-if="false" v-model.trim="vo.ctaMemberId" maxlength="20" placeholder="请输入中国跆协会员号" type="text" />
            <span v-else>{{ vo.ctaMemberId }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="中国跆协个人会员到期日" prop="ctaMemberExipry" :rules="vo.ctaMemberStatusCode === 'None' || !vo.ctaMemberStatusCode ? [] : formRules.ctaMemberExipry">
            <el-date-picker v-if="false" v-model="vo.ctaMemberExipry" type="date" value-format="yyyy-MM-dd" placeholder="请选择会员到期日" :clearable="false" style="width: 100%" />
            <span v-else>{{ vo.ctaMemberExipry ? vo.ctaMemberExipry.slice(0, 10) : '' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="省跆协会员号">
            <el-input v-if="!isCheck" v-model.trim="vo.ptkCode" placeholder="请输入省跆协会员号" type="text" />
            <span v-else>{{ vo.ptkCode }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <div class="gl_clear">
            <div class="gl_fl">
              <el-form-item label="上传中国跆拳道会员信息照片" prop="ctaMemberImageUrl1" :rules="vo.ctaMemberStatusCode === 'None' || !vo.ctaMemberStatusCode ? [] : formRules.ctaMemberImageUrl1">
                <div style="min-width: 300px" class="gl_clear">
                  <template v-for="(item, index) in imgList">
                    <div :key="index" class="upload_wrap gl_mr_15 gl_mb_15 gl_fl">
                      <upload-file
                        v-if="!isCheck"
                        ref="uploadFile"
                        class="imgt_upload"
                        :file-name="'照片'"
                        :action="action"
                        :show-file-list="false"
                        :limit="1"
                        file-type="image"
                        format-file=".jpg,.jpeg,.png"
                        :default-file-url="getStaticPhotoUrl(item)"
                        @uploadSuccess="photoSavePositive($event, index)"
                      />
                      <img v-if="isCheck" class="show_img" :src="getStaticPhotoUrl(item)">
                      <div v-if="!isCheck" class="imgDelWrap" @click="delImg(index)">
                        <i class="imgDelete el-icon-delete" />
                      </div>
                    </div>
                  </template>
                  <div v-if="imgList.length < maxImgLen && !isCheck" :style="{height: imgList.length ? '150px' : 'auto'}" class="addImgBtn gl_fl">
                    <el-button type="text" @click="addImgUploader">添加照片</el-button>
                  </div>
                </div>
              </el-form-item>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import uploadFile from './uploadFileDialog';

import {
  api_GET_Provinces, // 获取省列表(不包括子级)
  api_GET_CitiesProvinceCode, // 根据省的code查询市列表
  api_GET_CountiesCityCode // 根据市的code查询县列表
} from '@/extend/api/trainswaggerApi/district.js';

import { CopyData } from '@/lib';

import { ModMemberInfoVO } from '@/lib/form/train/enter.js';

export default {
  components: {
    uploadFile
  },
  props: {
    dict: {
      type: Object,
      default() {
        return {};
      }
    },
    // 传入的个人信息数据
    userData: {
      type: Object,
      default() {
        return {};
      }
    },
    isCheck: {
      type: Boolean,
      default: false
    },
    hideStyle: {
      type: Boolean,
      default: false
    },
    hideTitle: {
      type: Boolean,
      default: false
    },
    formSize: {
      type: String,
      default: 'medium'
    }
  },
  data () {
    return {
      action: `${WEB_CONFIG.VUE_APP_STATIC_FILE_RUL}/api/upload/image`, // 图片上传地址
      vo: new ModMemberInfoVO(),
      provinces: [], // 省字典
      cities: [], // 市字典
      counties: [], // 县字典
      maxImgLen: 6,
      imgList: [], // 照片存储
      formRules: {
        parentTAProvinceCode: [
          { required: true, message: '请选择所属协会', trigger: 'change' }
        ],
        ctaMemberId: [
          { required: true, message: '请输入中国台协会员号', trigger: 'blur' }
        ],
        ctaMemberExipry: [
          { required: true, message: '请选择中国跆协个人会员到期日', trigger: 'change' }
        ],
        ctaMemberImageUrl1: [
          { required: true, message: '请上传中国跆拳道会员信息照片', trigger: 'change' }
        ]
      }
    };
  },
  computed: {
    provincesName () {
      if (this.vo.parentTAProvinceCode) {
        const _provincesData = this.provinces.find(item => item.code === this.vo.parentTAProvinceCode);
        return _provincesData ? _provincesData.name : '';
      } else {
        return '';
      }
    },
    cityName () {
      if (this.vo.parentTACityCode !== null) {
        const _citiesData = this.cities.find(item => item.code === this.vo.parentTACityCode);
        return _citiesData ? _citiesData.name : '';
      } else {
        return '';
      }
    },
    countyName () {
      if (this.vo.parentTACountyCode !== null) {
        const _countyData = this.counties.find(item => item.code === this.vo.parentTACountyCode);
        return _countyData ? _countyData.name : '';
      } else {
        return '';
      }
    },
    registerMemberStatusName () {
      if (this.dict.registerMemberStatus) {
        const _rmsData = this.dict.registerMemberStatus.find(item => item.code === this.vo.ctaMemberStatusCode);
        return _rmsData ? _rmsData.value : '';
      } else {
        return '';
      }
    }
  },
  watch: {
    userData: {
      immediate: true,
      deep: true,
      handler(val) {
        if (val.id) {
          // 起始点
          CopyData(this.userData, this.vo);

          if (this.vo.parentTACityCode) {
            this.getCitiesAPI(this.vo.parentTAProvinceCode);
          }
          if (this.vo.parentTACountyCode) {
            this.getCountiesAPI(this.vo.parentTACityCode);
          }

          this.formatImgListFromMemberImg(val);
        } else {
          this.clearInsideUserData();
        }
      }
    }
  },
  created() {
    this.init();
  },
  methods: {
    // 初始化，非起始点
    init () {
      this.getProvincesAPI();
    },
    // 外部获取组件数据的方法
    getInsideUserData () {
      for (let i = 0; i < this.imgList.length; i++) {
        const item = this.imgList[i];
        this.vo['ctaMemberImageUrl' + (i + 1)] = item;
      }

      return new Promise((reslove, reject) => {
        this.$refs.refMemberInfo.validate((valid) => {
          if (valid) {
            reslove(this.vo);
          } else {
            reject({
              component: 'memberInfo',
              error: {
                msg: '校验失败'
              }
            });
          }
        });
      });
    },
    onChangeStatusCode () {
      this.$refs.refMemberInfo.clearValidate();
    },
    // 清空数据及验证
    clearInsideUserData () {
      this.vo = new ModMemberInfoVO();
      this.imgList = [];
      if (this.$refs.refMemberInfo) {
        this.$refs.refMemberInfo.resetFields();
      } else {
        this.$nextTick(() => {
          this.$refs.refMemberInfo.resetFields();
        });
      }
    },
    // 根据数据格式化图片数组
    formatImgListFromMemberImg (data) {
      const _keyList = [
        'ctaMemberImageUrl1',
        'ctaMemberImageUrl2',
        'ctaMemberImageUrl3',
        'ctaMemberImageUrl4',
        'ctaMemberImageUrl5',
        'ctaMemberImageUrl6'
      ];

      const _imgList = [];

      for (let i = 0; i < _keyList.length; i++) {
        const item = _keyList[i];
        if (data[item]) {
          _imgList.push(data[item]);
          this.vo[item] = '';
        }
      }
      this.imgList = _imgList;
    },
    // 删除图片
    delImg (index) {
      this.imgList.splice(index, 1);
    },
    // 切换省下拉菜单时
    onChangeProvinces (val) {
      this.cities = [];
      this.counties = [];
      this.vo.parentTACityCode = '';
      this.vo.parentTACountyCode = '';
      this.getCitiesAPI(val);
    },
    // 切换市下拉菜单时
    onChangeCities (val) {
      this.counties = [];
      this.vo.parentTACountyCode = '';
      if (val !== 'isNull') {
        this.getCountiesAPI(val);
      }
    },
    // 获取省API
    getProvincesAPI () {
      api_GET_Provinces()
        .then(res => {
          this.provinces = res;
        })
        .catch(
          error => {
            this.$message({
              message: `字典获取失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 获取市API
    getCitiesAPI (code) {
      api_GET_CitiesProvinceCode(code)
        .then(res => {
          this.cities = [{ code: null, name: '无' }, ...res];
        })
        .catch(
          error => {
            this.$message({
              message: `字典获取失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 获取县API
    getCountiesAPI (code) {
      api_GET_CountiesCityCode(code)
        .then(res => {
          this.counties = [{ code: null, name: '无' }, ...res];
        })
        .catch(
          error => {
            this.$message({
              message: `字典获取失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 获取静态文件
    getStaticPhotoUrl (relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 上传成功
    photoSavePositive (fileUrl, index) {
      // this.$set(this.vo, 'idCardImage', fileUrl.tempUrl);
      this.$set(this.imgList, index, fileUrl.tempUrl);
    },
    // 添加图片上传空间
    addImgUploader () {
      this.imgList.push('');
    }
  }
};
</script>

<style lang="scss" scoped>
  .imgt_upload {
    width: 240px;
    height: 150px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    overflow: hidden;
  }
  .imgt_upload.no_pointer {
    cursor: default;
  }
  .imgt_upload:hover {
    border-color: #409EFF;
  }

  .upload_wrap  {
    position:relative;
    overflow:hidden;
  }
  .imgDelWrap {
    position: absolute;
    top: -29px;
    right: -29px;
    width: 60px;
    height: 60px;
    cursor: pointer;
    transform: rotate(45deg);
    // background-color: rgba(255, 255, 255, 0.8);
  }
  .imgDelete {
    font-size: 18px;
    position: absolute;
    top: 37px;
    left: 21px;
    transform: rotate(-45deg);
    color: rgba(255, 0, 0, 0.8);
  }

  .addImgBtn {
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
  }
  .show_img {
    width: 240px;
    height: 150px;
    border-radius: 4px;
    vertical-align: middle;
  }
</style>
